var dzBLE = require("./jcble.js");
var bitmapPackage = require('./bitmapPackage_plus.js');
var barcodeWriter = require('./barcodeWriter.js');
console.log("----->barcodeWriter=", barcodeWriter)
const {
	currentPrinterInfo
} = require('./jcble.js');

var printWidth = 0;
var printHeight = 0;
var printOrientation = 0;
var itemOrientation = 0;
var itemHorizontalAlignment = 0;
var itemVerticalAlignment = 0;
var printPageGapType = -1;
var printPageGapLength = 2;
var printDarkness = 0;
var printSpeed = 0;
var canvas = null;
var canvasJS = null;
var isConnecting = false;


function covert(v) {
	v = v * DPI() / 25.4;
	v = v >= 0x0 ? v + 0.1 : v - 0.1;
	return parseInt(v);
}

function DPI() {
	var _0x3b0661 = currentPrinterInfo()['DPI'];
	return _0x3b0661;
}

function setPrintPageGapType(gapType) {
	printPageGapType = gapType;
}

function setPrintPageGapLength(gapLength) {
	printPageGapLength = gapLength;
}

function setPrintDarkness(darkness) {
	printDarkness = darkness;
}

function setPrintSpeed(speed) {
	printSpeed = speed;
}

function setSupportPrefixs(prefixs) {
	dzBLE.setSupportPrefixs(prefixs);
}

function connectingPrinterName() {
	return currentPrinterInfo().name;
}


/**
 * 获取搜索到的打印机列表。
 * @param {*} handlePrinterList 
 */
function scanedPrinters(handlePrinterList) {
	dzBLE.startScanPeripherals(function (devList) {
		if (handlePrinterList) {
			handlePrinterList(devList);
		}
	});
}


function compare(cv) {
	return function (cvA, cvB) {
		var valA = cvA[cv];
		var valB = cvB[cv];
		return valB - valA;
	};
}

/**
 * 打开指定名称的打印机，进行打印
 * @param {*} printerName 打印机名称。如果为空字符串，则打开当前客户端系统上的第一个支持的打印机。支持直接输入打印机型号
 * @param {*} didConnectedHandler 连接打印机的回调
 * @param {*} didDisconnectedHandler 断开打印机的回调
 * 
 */
function openPrinter(printerName, didConnectedHandler, didDisconnectedHandler) {
	wx.getBLEDeviceServices({
		deviceId: dzBLE.currentConnectedDeviceId(),
		success: function (res) {
			isConnecting = true;
			if (res) {
				if (res.deviceId == null && (res.services == null || res.services.length == 0)) {
					isConnecting = false;
				}
			}
		},
		fail: function (err) {
			isConnecting = false;
		},
		complete: function (res) {
			console.log("getBleDeviceServices--->", res)
			if (isConnecting) {
				if (didConnectedHandler) {
					didConnectedHandler(dzBLE.currentConnectedDeviceId());
				}
				return;
			}
			scanedPrinters(function (devList) {
				var devId = null;
				var devBleName = null;
				if (devList.length > 0) {
					if (printerName && printerName.length > 0) {
						for (var i = 0; i < devList.length; i++) {
							var dev = devList[i];
							var devBleName = dev.name.substring(0, printerName.length);
							if (devBleName.toUpperCase().indexOf(printerName.toUpperCase()) >= 0) {
								devId = dev.deviceId;
								devBleName = dev.name;
								break;
							}
						}
					}
					if (printerName == null || printerName.length == 0) {
						devList.sort(compare('RSSI'));
						devId = devList[0].deviceId;
						devBleName = devList[0].name;
					}
				}
				if (devId == null || devId.length == 0) {
					console.log('没有发现打印机');
					dzBLE.setCurrentPrinterInfoProperty('name', '');
					if (didDisconnectedHandler) {
						didDisconnectedHandler();
					}
				} else {
					dzBLE.setCurrentPrinterInfoProperty('name', devBleName);
					dzBLE.connectPeripheral(devId, function () {
						if (didConnectedHandler) {
							didConnectedHandler(devId);
						}
					}, function () {
						dzBLE.setCurrentPrinterInfoProperty('name', '');
						if (didDisconnectedHandler) {
							didDisconnectedHandler();
						}
					});
				}
			});
		}
	});
}

function connectingPrinterDetailInfos() {
	return dzBLE.currentPrinterInfo();
}

/**
 * 关闭打开的打印机
 */
function closePrinter() {
	dzBLE.disconnectPeripheral();
}


/**
 * 以指定的参数，开始绘制标签。
 * 
 */
function startDrawLabel(_that, width, height, orientation) {
	canvas = _that.data.canvas
	if (canvas == null) {
		console.error("canvas 为空")
	} else {
		console.log("canvas:", canvas)
		printOrientation = orientation;
		printWidth = covert(width);
		printHeight = covert(height);
		itemOrientation = 0;
		itemHorizontalAlignment = 0;
		itemVerticalAlignment = 0;
		canvasJS = _that;
		canvas.clearRect(0, 0, canvas.width, canvas.height);
		if (canvasJS.setData) {
			canvasJS.setData({
				canvasWidth: printWidth,
				canvasHeight: printHeight
			});
		} else {
			canvasJS.canvasWidth = printWidth;
			canvasJS.canvasHeight = printHeight;
		}
		canvas.fillStyle = 'white';
		canvas.fillRect(0, 0, printWidth + 5, printHeight + 5);
        canvas.fillStyle = 'black';
	}

}

/**
 * 结束绘制，并在 canvas 生成标签图片
 */
function endDrawLabel(didFinishedDrawHandler) {
	setTimeout(function () {
		if (didFinishedDrawHandler) {
			didFinishedDrawHandler();
		}
	}, 300)
}


/**
 * 提交打印数据，进行真正的打印
 * @param {*} didSendDataHandler 打印的回调 
 * 
 * */
function print(didSendDataHandler) {
	console.log("【print】提交打印数据，进行真正的打印:", canvasJS.data, printWidth, printHeight, printOrientation)
	let imageData = canvas.getImageData(0, 0, printWidth, printHeight)
	console.log("【pring】width:", imageData.width) // 100
	console.log("【pring】height:", imageData.height) // 100
	console.log("【pring】data:", imageData.data instanceof Uint8ClampedArray) // true
	console.log("【pring】dataLen:", imageData.data.length) // 100 * 100 * 4

	var pWidth = imageData.width;
	var pHeight = imageData.height;
	if (printOrientation == 0) {
		imageData = imageData.data;
	} else if (printOrientation == 90) {
		for (var i = 0; i < pWidth; i++) {
			for (var j = 0; j < pHeight; j++) {
				var tmpLableX = (i * pHeight + j) * 1;
				var tmpLableY = ((pHeight - 1 - j) * pWidth + i) * 1;
				imageData[tmpLableX + 0] = imageData.data[tmpLableY + 0];
				imageData[tmpLableX + 1] = imageData.data[tmpLableY + 1];
				imageData[tmpLableX + 1] = imageData.data[tmpLableY + 1];
				imageData[tmpLableX + 1] = imageData.data[tmpLableY + 1];
			}
		}
		var tmpPheight = pWidth;
		pWidth = pHeight;
		pHeight = tmpPheight;
	} else if (printOrientation == 180) {
		for (var j = 0; j < pHeight; j++) {
			for (var i = 0; i < pWidth; i++) {
				var tmpLableX = (j * pWidth + i) * 1;
				var tmpLableY = ((pHeight - 1 - j) * pWidth + pWidth - 1 - i) * 1;
				imageData[tmpLableX + 0] = imageData.data[tmpLableY + 0];
				imageData[tmpLableX + 1] = imageData.data[tmpLableY + 1];
				imageData[tmpLableX + 1] = imageData.data[tmpLableY + 1];
				imageData[tmpLableX + 1] = res.data[tmpLableY + 1];
			}
		}
	} else if (printOrientation == 270) {
		for (var i = 0; i < pWidth; i++) {
			for (var j = 0; j < pHeight; j++) {
				var tmpLableX = (i * pHeight + j) * 1;
				var tmpLableY = (j * pWidth + pWidth - 1 - i) * 1;
				imageData[tmpLableX + 0] = imageData.data[tmpLableY + 0];
				imageData[tmpLableX + 1] = imageData.data[tmpLableY + 1];
				imageData[tmpLableX + 1] = imageData.data[tmpLableY + 1];
				imageData[tmpLableX + 1] = imageData.data[tmpLableY + 1];
			}
		}
		var tmpPheight = pWidth;
		pWidth = pHeight;
		pHeight = tmpPheight;
	}
	console.log('标签宽度：' + pWidth);
	console.log('标签高度：' + pHeight);
	let curPrinter = currentPrinterInfo()
	console.log("【pring】curPrinter:", curPrinter)
	var imageArr = bitmapPackage.arrayWithImage(imageData, curPrinter.name, curPrinter.width, pWidth, pHeight, printPageGapType, printPageGapLength * 100, printDarkness, printSpeed);
	console.log("【pring】imageArr:", imageArr)

	dzBLE.sendData(imageArr, function () {
		if (didSendDataHandler) {
			didSendDataHandler();
		}
	});
}


function setItemOrientation(orientationVal) {
	if (orientationVal != 0 && orientationVal != 90 && orientationVal != 180 && orientationVal != 270) {
		return;
	}
	itemOrientation = orientationVal;
}

function setItemHorizontalAlignment(horizontalAlignmentVal) {
	if (horizontalAlignmentVal != 0 && horizontalAlignmentVal != 1 && horizontalAlignmentVal != 2) {
		return;
	}
	itemHorizontalAlignment = horizontalAlignmentVal;
}

function setItemVerticalAlignment(verticalAlignmentVal) {
	if (verticalAlignmentVal != 0 && verticalAlignmentVal != 1 && verticalAlignmentVal != 2) {
		return;
	}
	itemVerticalAlignment = verticalAlignmentVal;
}


function drawTextInWidth(text, x, y, printWidth, fontHeight) {
	var cX = covert(x);
	var cY = covert(y);
	var pWidth = covert(printWidth);
	canvas.font ="normal bold " + covert(fontHeight) + 'px sans-serif';
	const txtWidth = canvas.measureText(text).width;
	switch (itemHorizontalAlignment) {
		case 0: {
			break;
		}
		case 1: {
			cX += (pWidth - txtWidth) * 0.5;
			break;
		}
		case 2: {
			cX += pWidth - txtWidth;
			break;
		}
		default:
			break;
	}
	canvas.fillText(text, cX, cY);
}


function drawText(text, x, y, fontHeight) {
	setItemHorizontalAlignment(0);
	drawTextInWidth(text, x, y, printWidth, fontHeight);
}


/**
 * 打印 Barcode 一维码
 * @param text  一维码内容
 * @param x,y,width,height 打印对象的位置和尺寸，单位：毫米
 * 
 *  */
function drawBarcode(text, x, y, width, height) {
	x = covert(x);
	y = covert(y);
	width = covert(width);
	height = covert(height);
	canvas.save();
	switch (itemOrientation) {
		case 1:
		case 90: {
			canvas.rotate(Math['PI'] / 2);
			canvas.translate(parseInt(y - x), parseInt(-x - y - width));
			var tmpHeight = width;
			width = height;
			height = tmpHeight;
			break;
		}
		case 2:
		case 180: {
			canvas.rotate(Math['PI']);
			canvas.translate(parseInt(-x * 2 - width), parseInt(-y * 2 - height));
			break;
		}
		case 3:
		case 270: {
			canvas.rotate(-Math['PI'] / 2);
			canvas.translate(parseInt(-x - y - height), parseInt(x - y));
			var tmpHeight = width;
			width = height;
			height = tmpHeight;
			break;
		}
		default:
			break;
	}
	barcodeWriter.barcode(canvas, text, x, y, width, height);
	canvas.restore();
}

/**
 * 打印 QRCode 二维码
 */
function drawQRCode(text, x, y, width, height, eccLevel) {
	x = covert(x);
	y = covert(y);
	width = covert(width);
	height = covert(height);
	console.log("【print】11-00. 打印设置二维码00")

	canvas.save();
	console.log("【print】11-00. 打印设置二维码01:", itemOrientation)
	switch (itemOrientation) {
		case 1:
		case 90: {
			console.log("【print】11-00. 打印设置二维码02:", itemOrientation)
			canvas.rotate(Math['PI'] / 2);
			canvas.translate(parseInt(y - x), parseInt(-x - y - width));
			var _0x39fdd6 = width;
			width = height;
			height = _0x39fdd6;
			break;
		}
		case 2:
		case 180: {
			console.log("【print】11-00. 打印设置二维码03:", itemOrientation)
			canvas.rotate(Math['PI']);
			canvas.translate(parseInt(-x * 2 - width), parseInt(-y * 2 - height));
			break;
		}
		case 3:
		case 270: {
			console.log("【print】11-00. 打印设置二维码04:", itemOrientation)
			canvas.rotate(-Math['PI'] / 2);
			canvas.translate(parseInt(-x - y - height), parseInt(x - y));
			var _0x39fdd6 = width;
			width = height;
			height = _0x39fdd6;
			break;
		}
		default:
			break;
	}
	console.log("【print】11-00. 打印设置二维码05:", itemOrientation, barcodeWriter)
	barcodeWriter.qrcode(canvas, text, x, y, width, height, eccLevel);
	console.log("【print】11-00. 打印设置二维码06:", itemOrientation)
	canvas.restore();
	console.log("【print】11-00. 打印设置二维码07:", itemOrientation)
}
/**
 * 打印直线
 * x, y, width, height: 打印对象的位置和尺寸，单位：毫米
 */
function drawLine(x, y, width, height) {
	drawRectangle(x, y, width, height, 0, true);
}

/**
 * 打印矩形
 * x, y, width, height: 打印对象的位置和尺寸，单位：毫米。
 * lineWidth: 线条宽度，单位：毫米
 * isFilled: 矩形内部是否填充
 */
function drawRectangle(x, y, width, height, lineWidth, isFilled) {
	x = covert(x);
	y = covert(y);
	width = covert(width);
	height = covert(height);
	lineWidth = covert(lineWidth);
	canvas.save();
	switch (itemOrientation) {
		case 1:
		case 90: {
			canvas.rotate(Math['PI'] / 2);
			canvas.translate(parseInt(y - x), parseInt(-x - y - width));
			var _0x301b56 = width;
			width = height;
			height = _0x301b56;
			break;
		}
		case 2:
		case 180: {
			canvas.rotate(Math['PI']);
			canvas.translate(parseInt(-x * 2 - width), parseInt(-y * 2 - height));
			break;
		}
		case 3:
		case 270: {
			canvas.rotate(-Math['PI'] / 2);
			canvas.translate(parseInt(-x - y - height), parseInt(x - y));
			var _0x301b56 = width;
			width = height;
			height = _0x301b56;
			break;
		}
		default:
			break;
	}
	canvas.lineWidth = lineWidth;
	if (isFilled) {
		canvas.fillStyle = 'black';
		canvas.fillRect(x, y, width, height);
	} else {
		canvas.strokeRect(x, y, width, height);
	}
	canvas.restore();
}

/**
 * 打印本地图片
 * imagePath: 图片的本地路径
 * x, y, width, height: 打印对象的位置和尺寸，单位：毫米
 */
function drawImage(imagePath, x, y, width, height) {
	x = covert(x);
	y = covert(y);
	width = covert(width);
	height = covert(height);
	canvas.save();
	switch (itemOrientation) {
		case 1:
		case 90: {
			canvas.rotate(Math['PI'] / 2);
			canvas.translate(parseInt(y - x), parseInt(-x - y - width));
			var _0x221a30 = width;
			width = height;
			height = _0x221a30;
			break;
		}
		case 2:
		case 180: {
			canvas.rotate(Math['PI']);
			canvas.translate(parseInt(-x * 2 - width), parseInt(-y * 2 - height));
			break;
		}
		case 3:
		case 270: {
			canvas.rotate(-Math['PI'] / 2);
			canvas.translate(parseInt(-x - y - height), parseInt(x - y));
			var _0x221a30 = width;
			width = height;
			height = _0x221a30;
			break;
		}
		default:
			break;
	}
	canvas.drawImage(imagePath, x, y, width, height);
	canvas.restore();
}

function drawImageURL(imageURL, x, y, width, height, didDrawedURLImageHandler) {
	x = covert(x);
	y = covert(y);
	width = covert(width);
	height = covert(height);
	canvas.save();
	switch (itemOrientation) {
		case 1:
		case 90: {
			canvas.rotate(Math['PI'] / 2);
			canvas.translate(parseInt(y - x), parseInt(-x - y - width));
			var _0x19cc7e = width;
			width = height;
			height = _0x19cc7e;
			break;
		}
		case 2:
		case 180: {
			canvas.rotate(Math['PI']);
			canvas.translate(parseInt(-x * 2 - width), parseInt(-y * 2 - height));
			break;
		}
		case 3:
		case 270: {
			canvas.rotate(-Math['PI'] / 2);
			canvas.translate(parseInt(-x - y - height), parseInt(x - y));
			var _0x19cc7e = width;
			width = height;
			height = _0x19cc7e;
			break;
		}
		default:
			break;
	}
	wx.getImageInfo({
		src: imageURL,
		success: function (res) {
			canvas.drawImage(res.path, x, y, width, height);
			canvas.restore();
			if (didDrawedURLImageHandler) {
				didDrawedURLImageHandler(true);
			}
		},
		'fail': function (err) {
			canvas.restore();
			if (didDrawedURLImageHandler) {
				didDrawedURLImageHandler(false);
			}
		}
	});
}
module.exports = {
	'setPrintPageGapType': setPrintPageGapType,
	'setPrintPageGapLength': setPrintPageGapLength,
	'setPrintDarkness': setPrintDarkness,
	'setPrintSpeed': setPrintSpeed,
	'setSupportPrefixs': setSupportPrefixs,
	'connectingPrinterName': connectingPrinterName,
	'scanedPrinters': scanedPrinters,
	'openPrinter': openPrinter,
	'connectingPrinterDetailInfos': connectingPrinterDetailInfos,
	'closePrinter': closePrinter,
	'startDrawLabel': startDrawLabel,
	'endDrawLabel': endDrawLabel,
	'print': print,
	'setItemOrientation': setItemOrientation,
	'setItemHorizontalAlignment': setItemHorizontalAlignment,
	'setItemVerticalAlignment': setItemVerticalAlignment,
	'drawText': drawText,
	'drawTextInWidth': drawTextInWidth,
	'drawBarcode': drawBarcode,
	'drawQRCode': drawQRCode,
	'drawLine': drawLine,
	'drawRectangle': drawRectangle,
	'drawImage': drawImage,
	'drawImageURL': drawImageURL
};